import os
import requests
from dotenv import load_dotenv
from openai import OpenAI


class QuestionGenerator:
    def __init__(self):
        # 加载环境变量
        load_dotenv(os.path.join(os.path.dirname(os.getcwd()), ".env"))
        load_dotenv()

        # 初始化百炼大模型客户端
        self.client = OpenAI(
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
        )

    def run(
        self,
        knowledge_point: str,
        num_questions: int,
        question_type: str,
    ):
        exam_type = None
        if "中考" in knowledge_point:
            exam_type = "中考"
        elif "高考" in knowledge_point:
            exam_type = "高考"

        # 🔍 第1步：检索知识点
        print("\n 正在检索知识点定义……")
        search_results = self.search_web(knowledge_point)
        print("\n===  检索到的知识点定义 ===\n")
        print(search_results)

        # 📝 第2步：生成习题
        print("\n 正在生成习题……")
        generate_prompt = self.build_question_prompt(
            knowledge_point, num_questions, question_type, search_results
        )
        questions_markdown = self.ask_llm(generate_prompt)
        print("\n===  生成的习题 ===\n")
        print(questions_markdown)

        # 🧐 第3步：验证答案
        print("\n 正在验证习题……")
        validation_result = self.validate_questions(questions_markdown, search_results)
        print("\n=== 验证结果 ===\n")
        print(validation_result)

        final_output = f"""
{questions_markdown}

---

## 验证结果

{validation_result}
"""

        # 📚 第4步：历年真题
        if exam_type:
            print(f"\n 检测到 {exam_type} 题型要求，正在检索历年真题……")
            past_exam_results = self.search_web(
                f"{knowledge_point} {exam_type} 历年真题"
            )
            print("\n===  检索到的历年真题原文 ===\n")
            print(past_exam_results)

            true_questions_md = self.organize_past_exams(
                exam_type, past_exam_results
            )

            final_output += f"""

---

# 历年{exam_type}真题

{true_questions_md}
"""

        # 💾 保存 Markdown
        filename = f"{knowledge_point.replace(' ', '_')}_习题.md"
        # with open(filename, "w", encoding="utf-8") as f:
        #     f.write(final_output)
        #
        # print(f"\n 已将结果保存到 {filename}")
        return final_output

    def search_web(self, query):
        """
        可替换成任意检索API
        这里用 tavily 公开接口作为示例
        """
        print(f"正在通过搜索引擎检索: {query}")
        url = "https://api.tavily.com/search"
        headers = {"Authorization": f"Bearer {os.getenv('TAVILY_API_KEY')}"}
        resp = requests.get(url, params={"query": query}, headers=headers, timeout=10)
        if resp.ok:
            data = resp.json()
            return data.get("summary", "未找到定义")
        else:
            return "未找到定义"

    def ask_llm(self, prompt: str) -> str:
        response = self.client.chat.completions.create(
            model="qwen-plus",
            messages=[
                {"role": "system", "content": "你是一位专业的教育助手。"},
                {"role": "user", "content": prompt},
            ]
        )
        return response.choices[0].message.content.strip()

    def build_question_prompt(
        self, knowledge_point, num_questions, question_type, search_results
    ):
        return f"""
你是一位优秀的教师。
请根据以下知识点生成 **{num_questions} 道 {question_type}** 习题。
每道题目必须包含：
- 题干
- 正确答案
- 解析说明

输出请严格按照以下 Markdown 格式：

# {knowledge_point} 习题

## 题目 1
> **题干：** ……
> 
> **答案：** ……
> 
> **解析：** ……

## 题目 2
> **题干：** ……
> 
> **答案：** ……
> 
> **解析：** ……

## ……

知识点参考定义如下：
{search_results}
"""

    def validate_questions(self, questions_markdown, search_results):
        validate_prompt = f"""
请根据以下知识点验证这些习题及答案的正确性并指出问题，如果没有问题请回复“验证通过”。

知识点：
{search_results}

习题及答案：
{questions_markdown}
"""
        return self.ask_llm(validate_prompt)

    def organize_past_exams(self, exam_type, past_exam_results):
        organize_prompt = f"""
请根据以下检索结果，从中整理出 5 道历年来 {exam_type} 真题，要求每道题包含：
- 题干
- 正确答案
- 简要解析
输出格式为 Markdown。
检索结果：
{past_exam_results}
"""
        return self.ask_llm(organize_prompt)


if __name__ == "__main__":
    generator = QuestionGenerator()

    knowledge_point = input("请输入知识点: ").strip()
    num_questions = int(input("请输入题目数量: ").strip())
    question_type = input("请输入题目类型（选择题/填空题/简答题/混合）: ").strip()

    a=generator.run(
        knowledge_point=knowledge_point,
        num_questions=num_questions,
        question_type=question_type
    )
    print(a)